<template>
  <div class="main">
    <div class="mortgage-calculator">
      <div class="header">
        <h1>房贷计算器</h1>
        <p>计算您的月供和还款计划</p>
      </div>

      <div class="main-content">
        <!-- 输入区域 -->
        <div class="input-section">
          <div class="calculator-card">
            <h2 class="section-title">贷款信息</h2>

            <div class="input-grid">
              <div class="input-group">
                <label for="loanAmount">贷款金额</label>
                <div class="input-with-unit">
                  <input
                    id="loanAmount"
                    type="number"
                    v-model.number="loanAmount"
                    placeholder="请输入贷款金额"
                    min="10000"
                    step="10000"
                  />
                  <span class="unit">元</span>
                </div>
                <div class="input-range">
                  <input
                    type="range"
                    v-model.number="loanAmount"
                    min="10000"
                    max="10000000"
                    step="10000"
                  />
                </div>
              </div>

              <div class="input-group">
                <label for="loanTerm">贷款年限</label>
                <div class="input-with-unit">
                  <input
                    id="loanTerm"
                    type="number"
                    v-model.number="loanTerm"
                    placeholder="请输入贷款年限"
                    min="1"
                    max="30"
                  />
                  <span class="unit">年</span>
                </div>
                <div class="input-range">
                  <input type="range" v-model.number="loanTerm" min="1" max="30" />
                </div>
              </div>

              <div class="input-group">
                <label for="interestRate">贷款利率</label>
                <div class="input-with-unit">
                  <input
                    id="interestRate"
                    type="number"
                    v-model.number="interestRate"
                    placeholder="请输入贷款利率"
                    min="1"
                    max="20"
                    step="0.01"
                  />
                  <span class="unit">%</span>
                </div>
                <div class="input-range">
                  <input type="range" v-model.number="interestRate" min="1" max="20" step="0.1" />
                </div>
              </div>

              <div class="input-group">
                <label for="downPayment">首付金额</label>
                <div class="input-with-unit">
                  <input
                    id="downPayment"
                    type="number"
                    v-model.number="downPayment"
                    placeholder="请输入首付金额"
                    min="0"
                    :max="totalHousePrice"
                    step="10000"
                  />
                  <span class="unit">元</span>
                </div>
                <div class="input-range">
                  <input
                    type="range"
                    v-model.number="downPayment"
                    min="0"
                    :max="totalHousePrice"
                    step="10000"
                  />
                </div>
              </div>
            </div>

            <div class="additional-inputs">
              <div class="input-group">
                <label for="housePrice">房屋总价</label>
                <div class="input-with-unit">
                  <input
                    id="housePrice"
                    type="number"
                    v-model.number="totalHousePrice"
                    placeholder="请输入房屋总价"
                    min="10000"
                    step="10000"
                  />
                  <span class="unit">元</span>
                </div>
              </div>

              <div class="input-group">
                <label for="repaymentMethod">还款方式</label>
                <select id="repaymentMethod" v-model="repaymentMethod">
                  <option value="equalPrincipalAndInterest">等额本息</option>
                  <option value="equalPrincipal">等额本金</option>
                </select>
              </div>
            </div>

            <!-- 预设利率 -->
            <div class="preset-rates">
              <h4>预设利率</h4>
              <div class="rate-buttons">
                <button
                  v-for="rate in presetRates"
                  :key="rate.name"
                  class="rate-btn"
                  :class="{ active: interestRate === rate.value }"
                  @click="interestRate = rate.value"
                >
                  {{ rate.name }} ({{ rate.value }}%)
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 结果展示 -->
        <div class="result-section">
          <div class="results-card">
            <h2 class="section-title">计算结果</h2>

            <div class="summary-cards">
              <div class="summary-card">
                <div class="summary-icon">💰</div>
                <div class="summary-content">
                  <h3>月供金额</h3>
                  <div class="summary-value">{{ formatCurrency(monthlyPayment) }}</div>
                </div>
              </div>

              <div class="summary-card">
                <div class="summary-icon">📈</div>
                <div class="summary-content">
                  <h3>总利息</h3>
                  <div class="summary-value">{{ formatCurrency(totalInterest) }}</div>
                </div>
              </div>

              <div class="summary-card">
                <div class="summary-icon">🏠</div>
                <div class="summary-content">
                  <h3>总还款额</h3>
                  <div class="summary-value">{{ formatCurrency(totalPayment) }}</div>
                </div>
              </div>

              <div class="summary-card">
                <div class="summary-icon">⏱️</div>
                <div class="summary-content">
                  <h3>贷款比例</h3>
                  <div class="summary-value">{{ loanToValueRatio }}%</div>
                </div>
              </div>
            </div>

            <!-- 还款进度 -->
            <div class="payment-progress">
              <h3>还款构成</h3>
              <div class="progress-bar">
                <div
                  class="progress-segment principal"
                  :style="{ width: principalPercentage + '%' }"
                >
                  <span class="segment-label">本金 {{ formatCurrency(loanAmount) }}</span>
                </div>
                <div class="progress-segment interest" :style="{ width: interestPercentage + '%' }">
                  <span class="segment-label">利息 {{ formatCurrency(totalInterest) }}</span>
                </div>
              </div>
              <div class="progress-legend">
                <div class="legend-item">
                  <span class="legend-color principal"></span>
                  <span>本金 ({{ principalPercentage.toFixed(1) }}%)</span>
                </div>
                <div class="legend-item">
                  <span class="legend-color interest"></span>
                  <span>利息 ({{ interestPercentage.toFixed(1) }}%)</span>
                </div>
              </div>
            </div>

            <!-- 年度还款计划 -->
            <div class="yearly-breakdown">
              <h3>年度还款计划</h3>
              <div class="breakdown-chart">
                <div
                  v-for="(year, index) in yearlyBreakdown"
                  :key="index"
                  class="year-bar"
                  :style="{ height: year.height + '%' }"
                  :title="`第${year.year}年: ${formatCurrency(year.total)}`"
                >
                  <div
                    class="bar-fill principal"
                    :style="{ height: year.principalPercentage + '%' }"
                  ></div>
                  <div
                    class="bar-fill interest"
                    :style="{ height: year.interestPercentage + '%' }"
                  ></div>
                </div>
              </div>
              <div class="breakdown-legend">
                <div class="legend-item">
                  <span class="legend-color principal"></span>
                  <span>本金</span>
                </div>
                <div class="legend-item">
                  <span class="legend-color interest"></span>
                  <span>利息</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 详细还款计划 -->
          <div class="detailed-plan" v-if="showDetailedPlan">
            <h3>详细还款计划</h3>
            <div class="plan-table-container">
              <table class="plan-table">
                <thead>
                  <tr>
                    <th>期数</th>
                    <th>月供</th>
                    <th>本金</th>
                    <th>利息</th>
                    <th>剩余本金</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="payment in paymentPlan.slice(0, 60)" :key="payment.month">
                    <td>{{ payment.month }}</td>
                    <td>{{ formatCurrency(payment.monthlyPayment) }}</td>
                    <td>{{ formatCurrency(payment.principal) }}</td>
                    <td>{{ formatCurrency(payment.interest) }}</td>
                    <td>{{ formatCurrency(payment.remainingPrincipal) }}</td>
                  </tr>
                  <tr v-if="paymentPlan.length > 60">
                    <td colspan="5" class="more-rows">... 还有 {{ paymentPlan.length - 60 }} 期</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <button class="btn btn-outline" @click="exportToCSV">导出CSV</button>
          </div>
        </div>
      </div>

      <!-- 比较工具 -->
      <div class="comparison-section">
        <div class="comparison-card">
          <h2 class="section-title">利率对比</h2>
          <div class="comparison-chart">
            <div v-for="rate in comparisonRates" :key="rate.value" class="rate-comparison">
              <div class="rate-label">{{ rate.value }}%</div>
              <div class="rate-bar">
                <div class="bar-fill" :style="{ width: rate.percentage + '%' }"></div>
              </div>
              <div class="rate-value">{{ formatCurrency(rate.monthlyPayment) }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="footer">
        <p>房贷计算器 - 计算结果仅供参考，实际以银行审批为准</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

// 响应式数据
const loanAmount = ref(1000000)
const loanTerm = ref(30)
const interestRate = ref(4.5)
const downPayment = ref(300000)
const totalHousePrice = ref(1300000)
const repaymentMethod = ref('equalPrincipalAndInterest')
const showDetailedPlan = ref(false)

// 预设利率
const presetRates = [
  { name: '公积金贷款', value: 3.1 },
  { name: '商业贷款基准', value: 4.2 },
  { name: 'LPR基准', value: 4.5 },
  { name: '二套房', value: 5.2 },
  { name: '高利率', value: 6.0 }
]

// 计算属性
const monthlyPayment = computed(() => {
  if (repaymentMethod.value === 'equalPrincipalAndInterest') {
    return calculateEqualPrincipalAndInterest()
  } else {
    // 等额本金方式，返回首月月供
    return calculateEqualPrincipal()[0]?.monthlyPayment || 0
  }
})

const totalInterest = computed(() => {
  const plan = repaymentMethod.value === 'equalPrincipalAndInterest'
    ? calculateEqualPrincipalAndInterestPlan()
    : calculateEqualPrincipal()

  return plan.reduce((total, payment) => total + payment.interest, 0)
})

const totalPayment = computed(() => {
  return loanAmount.value + totalInterest.value
})

const loanToValueRatio = computed(() => {
  return ((loanAmount.value / totalHousePrice.value) * 100).toFixed(1)
})

const principalPercentage = computed(() => {
  return (loanAmount.value / totalPayment.value) * 100
})

const interestPercentage = computed(() => {
  return (totalInterest.value / totalPayment.value) * 100
})

const paymentPlan = computed(() => {
  if (repaymentMethod.value === 'equalPrincipalAndInterest') {
    return calculateEqualPrincipalAndInterestPlan()
  } else {
    return calculateEqualPrincipal()
  }
})

const yearlyBreakdown = computed(() => {
  const months = loanTerm.value * 12
  const yearlyData = []

  for (let year = 1; year <= loanTerm.value; year++) {
    const startMonth = (year - 1) * 12
    const endMonth = Math.min(year * 12, months)

    const yearPayments = paymentPlan.value.slice(startMonth, endMonth)
    const totalPrincipal = yearPayments.reduce((sum, p) => sum + p.principal, 0)
    const totalInterest = yearPayments.reduce((sum, p) => sum + p.interest, 0)
    const total = totalPrincipal + totalInterest

    // 计算柱状图高度（相对于最高年份）
    const maxTotal = Math.max(...Array.from({ length: loanTerm.value }, (_, i) => {
      const yStart = i * 12
      const yEnd = Math.min((i + 1) * 12, months)
      return paymentPlan.value.slice(yStart, yEnd).reduce((sum, p) => sum + p.monthlyPayment, 0)
    }))

    yearlyData.push({
      year,
      principal: totalPrincipal,
      interest: totalInterest,
      total,
      principalPercentage: (totalPrincipal / total) * 100,
      interestPercentage: (totalInterest / total) * 100,
      height: (total / maxTotal) * 100
    })
  }

  return yearlyData
})

const comparisonRates = computed(() => {
  const rates = [3.0, 4.0, 4.5, 5.0, 6.0]
  const maxPayment = Math.max(...rates.map(rate => {
    const monthlyRate = rate / 100 / 12
    const months = loanTerm.value * 12
    return loanAmount.value * monthlyRate * Math.pow(1 + monthlyRate, months) /
      (Math.pow(1 + monthlyRate, months) - 1)
  }))

  return rates.map(rate => {
    const monthlyRate = rate / 100 / 12
    const months = loanTerm.value * 12
    const payment = loanAmount.value * monthlyRate * Math.pow(1 + monthlyRate, months) /
      (Math.pow(1 + monthlyRate, months) - 1)

    return {
      value: rate,
      monthlyPayment: payment,
      percentage: (payment / maxPayment) * 100
    }
  })
})

// 计算方法
const calculateEqualPrincipalAndInterest = () => {
  const monthlyRate = interestRate.value / 100 / 12
  const months = loanTerm.value * 12

  if (monthlyRate === 0) {
    return loanAmount.value / months
  }

  return loanAmount.value * monthlyRate * Math.pow(1 + monthlyRate, months) /
    (Math.pow(1 + monthlyRate, months) - 1)
}

const calculateEqualPrincipalAndInterestPlan = () => {
  const monthlyRate = interestRate.value / 100 / 12
  const months = loanTerm.value * 12
  const monthlyPayment = calculateEqualPrincipalAndInterest()
  const plan = []

  let remainingPrincipal = loanAmount.value

  for (let month = 1; month <= months; month++) {
    const interest = remainingPrincipal * monthlyRate
    const principal = monthlyPayment - interest
    remainingPrincipal -= principal

    plan.push({
      month,
      monthlyPayment,
      principal,
      interest,
      remainingPrincipal: Math.max(0, remainingPrincipal)
    })
  }

  return plan
}

const calculateEqualPrincipal = () => {
  const monthlyRate = interestRate.value / 100 / 12
  const months = loanTerm.value * 12
  const monthlyPrincipal = loanAmount.value / months
  const plan = []

  let remainingPrincipal = loanAmount.value

  for (let month = 1; month <= months; month++) {
    const interest = remainingPrincipal * monthlyRate
    const monthlyPayment = monthlyPrincipal + interest
    remainingPrincipal -= monthlyPrincipal

    plan.push({
      month,
      monthlyPayment,
      principal: monthlyPrincipal,
      interest,
      remainingPrincipal: Math.max(0, remainingPrincipal)
    })
  }

  return plan
}

// 工具方法
const formatCurrency = (amount) => {
  return '¥' + amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const exportToCSV = () => {
  const headers = ['期数', '月供', '本金', '利息', '剩余本金']
  const csvContent = [
    headers.join(','),
    ...paymentPlan.value.map(payment => [
      payment.month,
      payment.monthlyPayment.toFixed(2),
      payment.principal.toFixed(2),
      payment.interest.toFixed(2),
      payment.remainingPrincipal.toFixed(2)
    ].join(','))
  ].join('\n')

  const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)

  link.setAttribute('href', url)
  link.setAttribute('download', `房贷还款计划_${new Date().toISOString().split('T')[0]}.csv`)
  link.style.visibility = 'hidden'

  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 监听房屋总价变化，自动调整贷款金额
watch(totalHousePrice, (newPrice) => {
  loanAmount.value = Math.max(0, newPrice - downPayment.value)
})

// 监听首付变化，自动调整贷款金额
watch(downPayment, (newDownPayment) => {
  loanAmount.value = Math.max(0, totalHousePrice.value - newDownPayment)
})

// 监听贷款金额变化，自动调整首付
watch(loanAmount, (newLoanAmount) => {
  downPayment.value = Math.max(0, totalHousePrice.value - newLoanAmount)
})
</script>

<style scoped>
.main {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(90deg, #2196f3 0%, #1976d2 100%);
}
.mortgage-calculator {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.header {
  background: linear-gradient(90deg, #2196f3 0%, #1976d2 100%);
  color: white;
  padding: 20px;
  text-align: center;
}

.header h1 {
  font-size: 28px;
  margin-bottom: 10px;
}

.header p {
  opacity: 0.9;
}

.main-content {
  padding: 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.input-section,
.result-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.calculator-card,
.results-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #2c3e50;
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
}

.input-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.input-group {
  margin-bottom: 20px;
}

.input-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #34495e;
}

.input-with-unit {
  position: relative;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-with-unit input {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  background: white;
}

.unit {
  position: absolute;
  right: 15px;
  color: #7f8c8d;
  font-size: 16px;
}

.input-range input {
  width: 100%;
  margin-top: 5px;
}

.additional-inputs {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.additional-inputs select {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  background: white;
}

.preset-rates {
  margin-top: 20px;
}

.preset-rates h4 {
  margin-bottom: 10px;
  color: #34495e;
}

.rate-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.rate-btn {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 16px;
}

.rate-btn.active {
  background: #2196f3;
  color: white;
  border-color: #2196f3;
}

.summary-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  margin-bottom: 25px;
}

.summary-card {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.summary-icon {
  font-size: 24px;
}

.summary-content h3 {
  margin: 0 0 5px;
  font-size: 16px;
  color: #7f8c8d;
}

.summary-value {
  font-size: 18px;
  font-weight: bold;
  color: #2196f3;
}

.payment-progress {
  margin-bottom: 25px;
}

.payment-progress h3 {
  margin-bottom: 15px;
  color: #2c3e50;
}

.progress-bar {
  display: flex;
  height: 40px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-segment {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: width 0.5s ease;
  position: relative;
}

.progress-segment.principal {
  background: #4caf50;
}

.progress-segment.interest {
  background: #ff9800;
}

.segment-label {
  color: white;
  font-size: 16px;
  font-weight: 500;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3);
}

.progress-legend {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #7f8c8d;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-color.principal {
  background: #4caf50;
}

.legend-color.interest {
  background: #ff9800;
}

.yearly-breakdown {
  margin-bottom: 25px;
}

.yearly-breakdown h3 {
  margin-bottom: 15px;
  color: #2c3e50;
}

.breakdown-chart {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  height: 200px;
  margin-bottom: 10px;
  padding: 10px 0;
}

.year-bar {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  height: 100%;
  min-height: 20px;
  position: relative;
  cursor: pointer;
}

.bar-fill {
  width: 100%;
  transition: height 0.5s ease;
}

.bar-fill.principal {
  background: #4caf50;
}

.bar-fill.interest {
  background: #ff9800;
}

.breakdown-legend {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.detailed-plan {
  margin-top: 20px;
}

.detailed-plan h3 {
  margin-bottom: 15px;
  color: #2c3e50;
}

.plan-table-container {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}

.plan-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
}

.plan-table th {
  background: #f5f5f5;
  padding: 12px 15px;
  text-align: left;
  font-weight: 500;
  color: #34495e;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
}

.plan-table td {
  padding: 10px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.plan-table tr:last-child td {
  border-bottom: none;
}

.more-rows {
  text-align: center;
  color: #7f8c8d;
  font-style: italic;
}

.comparison-section {
  padding: 0 20px 20px;
}

.comparison-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.comparison-chart {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.rate-comparison {
  display: flex;
  align-items: center;
  gap: 15px;
}

.rate-label {
  width: 60px;
  font-weight: 500;
  color: #34495e;
}

.rate-bar {
  flex: 1;
  height: 20px;
  background: #e0e0e0;
  border-radius: 10px;
  overflow: hidden;
}

.rate-bar .bar-fill {
  height: 100%;
  background: linear-gradient(90deg, #2196f3, #1976d2);
  transition: width 0.5s ease;
}

.rate-value {
  width: 100px;
  text-align: right;
  font-weight: 500;
  color: #2196f3;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s;
}

.btn-outline {
  background: transparent;
  border: 1px solid #ddd;
  color: #7f8c8d;
}

.btn-outline:hover {
  background: #f5f5f5;
}

.footer {
  background: #f8f9fa;
  padding: 15px;
  text-align: center;
  color: #7f8c8d;
  font-size: 16px;
}

@media (max-width: 768px) {
  .main-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .input-grid {
    grid-template-columns: 1fr;
  }

  .additional-inputs {
    grid-template-columns: 1fr;
  }

  .summary-cards {
    grid-template-columns: 1fr;
  }

  .rate-buttons {
    flex-direction: column;
  }

  .breakdown-chart {
    height: 150px;
  }

  .plan-table-container {
    max-height: 300px;
  }
}
</style>